package edu.csl.study.gateway.config;

import edu.csl.study.gateway.filter.CustomGatewayFilter;
import edu.csl.study.gateway.filter.GatewayRateLimitFilterByCpu;
import edu.csl.study.gateway.filter.GatewayRateLimitFilterByIp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

@Configuration
public class GatewayConfig {
    @Bean
    public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/custom/**")
                        .filters(f -> f.stripPrefix(1).filter(new CustomGatewayFilter()))
                        .uri("lb://core-server2")
                        .order(0)
                        .id("custom_filter")
                )
                .build();
    }
    @Bean
    public RouteLocator customerRouteLocatorRateLimitFilterByIp(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/rateLimit/**")
                        .filters(f -> f.stripPrefix(1).filter(new GatewayRateLimitFilterByIp(10,1, Duration.ofSeconds(1))))
                        .uri("lb://core-server2")
                        .id("gatewayRateLimitFilterByIp")
                ).build();
    }
    @Autowired
    private GatewayRateLimitFilterByCpu gatewayRateLimitFilterByCpu;
    @Bean
    public RouteLocator customerRouteLocatorRateLimitFilterByCpu(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/rateLimitCpu/**")
                        .filters(f -> f.stripPrefix(1).filter(gatewayRateLimitFilterByCpu))
                        .uri("lb://core-server2")
                        .id("gatewayRateLimitFilterByCpu")
                ).build();
    }
}
